package pers.wz;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ServerDemo {
    public static void main(String[] args) throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务已启动");
        while (true) {
            final Socket accept = serverSocket.accept();
            System.out.println("客户端连接");
            executorService.execute(new Runnable() {
                public void run() {
                    handle(accept);
                }
            });
        }
    }

    private static void handle(Socket accept) {
        try {
            System.out.println("线程id----" + Thread.currentThread().getId());
            System.out.println("线程name--" + Thread.currentThread().getName());
            InputStream inputStream = accept.getInputStream();
            byte[] b = new byte[1024];
            int read = inputStream.read(b);
            System.out.println("客户端消息：" + new String(b, 0, read));
            OutputStream outputStream = accept.getOutputStream();
            outputStream.write("没钱".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
